package com.ht.medicaltreatment.utils

import com.gym.baselib.utils.RxRunThread
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import java.util.concurrent.TimeUnit

class DownTimeUtils {
    companion object{
        fun downTime(maxTime:Long,onProgress:(Long)->Unit): Disposable {
            val disposable = Observable.interval(0,1,TimeUnit.SECONDS)
                .take(maxTime+1)
                .map{maxTime - it}
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    onProgress(it)
                }
            return disposable
        }

        //延迟500毫秒后，执行任务
        fun delayedTask(millSeconds:Long = 500,task: () -> Unit) {
            Observable.timer(millSeconds, TimeUnit.MILLISECONDS)
                .compose(RxRunThread.rxud())
                .subscribe { _ -> task() }
        }


        private var disposable:Disposable? = null
        fun formatDownTime(time: Int,onProgress:(String)->Unit,remainingTime:(Int)->Unit):Disposable{
            var date = time
            disposable = Observable.interval(0,1,TimeUnit.SECONDS)
                .take(time.toLong())
                .compose(RxRunThread.rxud())
                .subscribe {
                    val formatTime = getDownTime(--date)
                    onProgress(formatTime)
                    remainingTime(date)
                }
            return disposable!!
        }

        fun getDownTime(time:Int):String{
            var date = time
            val seconds = date % 60
            val min = date / 60 % 60
            val hour = date / 60 / 60 % 24
            val sb = StringBuilder()
            if(hour < 10){
                sb.append("0$hour").append(":")
            }else{
                sb.append("$hour")
            }
            if(min < 10){
                sb.append("0$min").append(":")
            }else{
                sb.append("$min").append(":")
            }
            if(seconds < 10){
                sb.append("0$seconds")
            }else{
                sb.append("$seconds")
            }
            return sb.toString()
        }
    }
}